package com.dongdongshop.jop;

import com.dongdongshop.mail.MyAuthenticator;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.TbUserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;

@Component
public class DDShopJop {

    @DubboReference
    private TbUserService service;
    /**
     *  测试任务
     * @return  这个方法有一个返回值,返回的是调度结果,这是他给咱们提供的,封装好的
     */
    @XxlJob(value = "demoTask") // 一定记得加注解,里面提供了三个属性
    public ReturnT demoTask(){
        try {
            List<TbUser> users = service.selectUserListIsSeven();
            if (users.size() <= 0) {
                return ReturnT.SUCCESS;
            }else {
                UserEmil(users);
                return ReturnT.SUCCESS;
            }
        }catch (Exception e){
            return ReturnT.SUCCESS;
        }
    }

    private void UserEmil(List<TbUser> list){
        //1.卫星
        Message message = null;

        //4.补充燃料
        Session session = null;

        //4.2
        Properties properties = null;
        properties = new Properties();
        //设置主机,端口,是否需要身份验证
        properties.put("mail.smtp.host","smtp.qq.com");
        properties.put("mail.smtp.port","25");
        properties.put("mail.smtp.auth","true");

        //4.1  //创建一个MyAuthenticator 用来实例化 Authenticator
        session = Session.getDefaultInstance(properties,
                new MyAuthenticator("1246218947@qq.com","djazlgcqnvdlhfhb"));

        //3.实例化message
        message = new MimeMessage(session);

        //设置消息的内容 3.1
        try {
            for (TbUser user : list) {
                if (user.getEmail() == null || user.getEmail().equals("")){
                    continue;
                }else {
                    //设置邮件主题
                    message.setSubject("来自东东商城");
                    //设置邮件内容
                    message.setText("现在上线立马获得苹果手机14maxpro");
                    //设置邮件发送方
                    InternetAddress address = new InternetAddress("1246218947@qq.com");
                    message.setFrom(address);
                    //设置邮件的接受方
                    message.setRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
                    //2.送卫星上天
                    Transport.send(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
